package com.sgb.jicai.view.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.jicai.R;
import com.sgb.jicai.databinding.ItemJoininJicaiListBinding;
import com.swgk.core.BR;
import com.swgk.core.util.TimeUtil;
import com.sgb.jicai.entity.JoinJicaiDetailEntity;
import com.sgb.link.utils.JiCaiEditInputFilter;
import com.sgb.link.utils.UnitListUtils;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.MToast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 加盟集采页面   列表的适配器-----实体类需更换
 */
public class JoinInJicaiListAdapter extends BaseRecycleAdapter<JoinJicaiDetailEntity.RecordDetailListEntity> {

    private Context context;
    private Calendar selectedDate = Calendar.getInstance();
    private TextView tvDescribe;
    private TextView tvShowmore;
    private long deadline;
    private EditText etPrice;
    private EditText etQuantity;
    private LinearLayout ll_materials;


    public JoinInJicaiListAdapter(Context context, List<JoinJicaiDetailEntity.RecordDetailListEntity> datas) {
        super(context, R.layout.item_joinin_jicai_list, datas);
        this.context = context;
    }

    @Override
    public void convert(ItemViewHolder holder, final JoinJicaiDetailEntity.RecordDetailListEntity entity) {
        holder.setBinding(BR.viewModel, entity);
        tvDescribe = ((ItemJoininJicaiListBinding) holder.getmBinding()).tvDescribe;
        tvShowmore = ((ItemJoininJicaiListBinding) holder.getmBinding()).tvShowmore;
        //etPrice = ((ItemJoininJicaiListBinding) holder.getmBinding()).etPrice;  // V1。17 版本删除预期价格
        etQuantity = ((ItemJoininJicaiListBinding) holder.getmBinding()).etQuantity;
        ll_materials = ((ItemJoininJicaiListBinding) holder.getmBinding()).llMaterials;
        if (entity.getGroupbuyClass()==1){
            ll_materials.setVisibility(View.VISIBLE);
        }else {
            ll_materials.setVisibility(View.GONE);
        }
        //小数点后保留两位数字
        if (UnitListUtils.getUnitStart(entity.getUnitName())){
            etQuantity.setFilters(new JiCaiEditInputFilter[]{new JiCaiEditInputFilter(999999.999, 0.001,3)});
        }else {
            etQuantity.setFilters(new JiCaiEditInputFilter[]{new JiCaiEditInputFilter(999999, 1,0)});
        }
        ((ItemJoininJicaiListBinding) holder.getmBinding()).tvTime.setOnClickListener(view ->
                showCourseTimePop(((ItemJoininJicaiListBinding) holder.getmBinding()).tvTime, entity, 1));

        ((ItemJoininJicaiListBinding) holder.getmBinding()).tvExittime.setOnClickListener(view ->
                showCourseTimePop(((ItemJoininJicaiListBinding) holder.getmBinding()).tvExittime, entity, 2));

        ((ItemJoininJicaiListBinding) holder.getmBinding()).etQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())){
                    if (Double.valueOf(s.toString())>0){
                        entity.setOwnNum(s.toString().trim());
                    }else {
                        MToast.showToast(context,"请重新输入供应量，供应量必须大于0");
                    }
                }else {
                    entity.setOwnNum("");
                }
            }
        });


        try {
            //获取省略的字符数，0表示没和省略
            int ellipsisCount = tvDescribe.getLayout().getEllipsisCount(tvDescribe.getLineCount() - 1);
            tvDescribe.getLayout().getEllipsisCount(tvDescribe.getLineCount() - 1);
            //ellipsisCount>0说明没有显示全部，存在省略部分。
            if (ellipsisCount > 0) {
                //展示全部，按钮设置为点击收起。
                tvShowmore.setVisibility(View.VISIBLE);
            } else {
                tvShowmore.setVisibility(View.GONE);
            }
        } catch (Exception e) {

        }

        //设置预期价格和采购量不可编辑-----接口不给，手动临时加的判断，可替换
        try {
            if (entity.getGroupbuyClass() == 1) {//商品
//            当前时间大于商品的提货时间时不可修改
                if (null != entity.getPickTime() && !entity.getPickTime().isEmpty() && entity.getPickTime().length() > 0) {
                    long time = TimeUtil.getLongTime(entity.getPickTime(), "yyyy-MM-dd");
                    if (TimeUtil.getLongTime(TimeUtil.getDateStringYMD(System.currentTimeMillis()),"yyyy-MM-dd")> time) {
//                        etPrice.setFocusable(false);  // V1。17 版本删除预期价格
//                        etPrice.setFocusableInTouchMode(false);
                        etQuantity.setFocusable(false);
                        etQuantity.setFocusableInTouchMode(false);
                    } else {
//                        etPrice.setFocusableInTouchMode(true);
//                        etPrice.setFocusable(true);
//                        etPrice.requestFocus();
                        etQuantity.setFocusableInTouchMode(true);
                        etQuantity.setFocusable(true);
                        etQuantity.requestFocus();
                    }
                }
            } else {
//                当前时间大于入场时间不可编辑
                if (null != entity.getEntranceTime() && !entity.getEntranceTime().isEmpty() && entity.getEntranceTime().length() > 0) {
                    long time = TimeUtil.getLongTime(entity.getEntranceTime(), "yyyy-MM-dd");
                    if (TimeUtil.getLongTime(TimeUtil.getDateStringYMD(System.currentTimeMillis()),"yyyy-MM-dd")> time) {
//                        etPrice.setFocusable(false);
//                        etPrice.setFocusableInTouchMode(false);
                        etQuantity.setFocusable(false);
                        etQuantity.setFocusableInTouchMode(false);
                    } else {
//                        etPrice.setFocusableInTouchMode(true);
//                        etPrice.setFocusable(true);
//                        etPrice.requestFocus();
                        etQuantity.setFocusableInTouchMode(true);
                        etQuantity.setFocusable(true);
                        etQuantity.requestFocus();
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    //时间选择
    private void showCourseTimePop(TextView tvTime, JoinJicaiDetailEntity.RecordDetailListEntity entity, int type) {
        try {
            if (entity.getGroupbuyClass() == 1) {//商品
//            当前时间大于商品的提货时间时不可修改
                if (null != entity.getPickTime() && !entity.getPickTime().isEmpty() && entity.getPickTime().length() > 0) {
                    long time = TimeUtil.getLongTime(entity.getPickTime(), "yyyy-MM-dd");
                    long timeDay = TimeUtil.getLongTime(TimeUtil.getDateStringYMD(System.currentTimeMillis()), "yyyy-MM-dd");
                    if (timeDay > time) {
                        MToast.showToast(context, "当前时间大于商品的提货时间时不可修改");
                        return;
                    }
                }
            } else {
//                当前时间大于入场时间不可编辑
                if (null != entity.getEntranceTime() && !entity.getEntranceTime().isEmpty() && entity.getEntranceTime().length() > 0) {
                    long time = TimeUtil.getLongTime(entity.getEntranceTime(), "yyyy-MM-dd");
                    long timeDay = TimeUtil.getLongTime(TimeUtil.getDateStringYMD(System.currentTimeMillis()), "yyyy-MM-dd");
                    if (timeDay > time) {
                        MToast.showToast(context, "当前时间大于入场时间不可修改");
                        return;
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar dayCalendar = Calendar.getInstance();
        if (deadline < 100) {//时间戳
            dayCalendar.setTime(new Date());
        } else {
            dayCalendar.setTime(TimeUtil.getDateFromFormatString(TimeUtil.getDateStringYMD(deadline)));//非商品的入场时间和结束时间需在报价截止时间后
        }
        dayCalendar.add(Calendar.DAY_OF_MONTH, 0);
        TimePickerView timePicker = new TimePickerBuilder(context, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                tvTime.setText(format);
                selectedDate.setTime(date);
                if (type == 1) {
                    if (entity.getGroupbuyClass() == 1) {//商品-提货时间
//                        entity.setPickTime(format);
                        entity.setPickTime(String.valueOf(TimeUtil.getLongTime(format, "yyyy-MM-dd")));
                    } else {//非商品-进场时间
//                        entity.setEntranceTime(format);
                        entity.setEntranceTime(String.valueOf(TimeUtil.getLongTime(format, "yyyy-MM-dd")));

                        String entranceTime = entity.getEntranceTime();
                        String exitTime = entity.getExitTime();
                        if (!entranceTime.isEmpty() && !exitTime.isEmpty() && TimeUtil.getLongTime(entranceTime, "yyyy-MM-dd") > 100 && TimeUtil.getLongTime(exitTime, "yyyy-MM-dd") > 100) {
                            if (TimeUtil.getLongTime(entranceTime, "yyyy-MM-dd") >= TimeUtil.getLongTime(exitTime, "yyyy-MM-dd")) {
                                MToast.showToast(context, "入场时间应小于结束时间");
                                return;
                            }
                        }
                    }
                } else {
//                    entity.setExitTime(format);
                    entity.setExitTime(String.valueOf(TimeUtil.getLongTime(format, "yyyy-MM-dd")));

                    String entranceTime = entity.getEntranceTime();
                    String exitTime = entity.getExitTime();
                    if (!entranceTime.isEmpty() && !exitTime.isEmpty() && TimeUtil.getLongTime(entranceTime, "yyyy-MM-dd") > 100 && TimeUtil.getLongTime(exitTime, "yyyy-MM-dd") > 100) {
                        if (TimeUtil.getLongTime(entranceTime, "yyyy-MM-dd") >= TimeUtil.getLongTime(exitTime, "yyyy-MM-dd")) {
                            MToast.showToast(context, "结束时间应大于入场时间");
                            return;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }


    public void setOfferEndtime(long deadline) {
        this.deadline = deadline;
    }
}
